/*************************************************************************
	> File Name: thread.h
	> Author: luqingliang
	> Mail: 13420685558@163.com
	> Created Time: 2024年02月13日 星期二 19时34分45秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <pthread.h>

#define THREAD_WORK_MAX 64

// 线程工作状态
enum
{
	T_FREE = 0,
	T_LIVE,
	T_FINISH,
	T_DIE,
};

typedef struct thread_work_st
{
	int id;		// work id
	int status; // work status
	pthread_t tid;
	void *(*work_func)(void *); // be called function
	void *arg;					// args
	void *ret;					// be called function
} thread_work_t;

// 简易线程池
thread_work_t pool[THREAD_WORK_MAX];

// 最后线程池地址
thread_work_t *pptr = pool;

// 外层包装
void *work_impl(void *worker)
{
	thread_work_t *tmp = (thread_work_t *)worker;
	tmp->ret = tmp->work_func(tmp->arg);
	tmp->status = T_FINISH;
	// printf("id:%d finish ret :%d\n", tmp->id, *(int *)tmp->ret);
	pthread_exit(tmp->ret);
}

// 用户创建任务函数
int create(void *func, void *arg)
{
	// 确保没有越界
	assert(pptr - pool < THREAD_WORK_MAX);
	*pptr = (thread_work_t){
		.id = pptr - pool,
		.status = T_LIVE,
		.work_func = func,
		.arg = arg,
		.ret = NULL,
	};
	if (pthread_create(&(pptr->tid), NULL, work_impl, pptr) == 0)
	{
		// printf("id:%d thread id:%ld func:%p arg:%p\n", pptr->id, pptr->tid, pptr->work_func, pptr->arg);
		int id = pptr->id;
		++pptr;
		return id;
	}
	return -1;
}

// 用户回收所有线程函数
void join()
{
	for (int i = 0; i < THREAD_WORK_MAX; i++)
	{
		thread_work_t *t = &pool[i];
		if (t->status == T_LIVE || t->status == T_FINISH)
		{
			pthread_join(t->tid, NULL);
			t->status = T_DIE;
		}
	}
}

// man 3 atexit
__attribute__((destructor)) void cleanup()
{
	join();
}
